﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Rison.Web.Common;
using Rison.BusinessFacade.Helper;
using Rison.BusinessFacade.Common;
using Rison.BusinessFacade.Entity.ZP;
using Rison.BusinessFacade.Facade.ZP;
using Rison.DataAccess.Common;
using Rison.BusinessFacade.Facade.NRBZ;
using Rison.BusinessFacade.Entity.NRBZ;
using System.IO;

namespace Rison.Web.ZP
{
    public partial class YxsbDetail : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                LabTBRQ.Text = "填报日期：" + System.DateTime.Today.ToShortDateString();
                if (!string.IsNullOrEmpty(departid))
                {
                    //BindDate();
                    GetAnlx();
                }

                if (!string.IsNullOrEmpty(key))
                {
                    ReLoadInformation();
                    NrbzFacade facade = new NrbzFacade();

                    DataSet ds = facade.LoadAttachement(key, 9);
                    DataList9.DataSource = ds.Tables[0];
                    DataList9.DataBind();
                   
                } 
                
            }       
        }

        //private void BindDate()
        //{
        //    YxsbFacade facade = new YxsbFacade();

        //    this.DataList1.DataSource = departid == "" ? null : facade.GetYxsbList(departid, year);
        //    this.DataList1.DataBind();

        //}

        public string departid
        {
            get 
            { 
                if(ViewState["departid"]==null)
                {
                    if(!string.IsNullOrEmpty(Request.QueryString["DepartID"]))
                    {
                        ViewState["departid"]=Request.QueryString["DepartID"].ToString();
                        return ViewState["departid"].ToString();
                    }
                }
                else
                   return ViewState["departid"].ToString();

                return "";
            }
            set
            {
                ViewState["departid"]=value;
            }
        }

        private string year
        {
            get 
            {
                if (ViewState["year"]==null)
                    return System.DateTime.Today.Year.ToString();
                else
                    return ViewState["year"].ToString();
            }
            set { ViewState["year"] = value; }
        }            

        protected override string key
        {
            get
            {
                if (ViewState["id"] != null)
                    return ViewState["id"].ToString();

                if (!string.IsNullOrEmpty(Request.QueryString["id"]))
                {
                    ViewState["id"] = Request.QueryString["id"].ToString();
                    return ViewState["id"].ToString();
                }

                return "";
            }
        }

        private string userid
        {
            get { return CurrentLoginedUser.UserId; }
        }

        private void ReLoadInformation()
        {
            YxsbFacade facade = new YxsbFacade();
            DataRow dr = facade.GetYxsbRow(key);
            if (dr != null)
            {

                this.TextBox1.Text = dr["Title"].ToString();
                FCKeditor1.Value = dr["Content"].ToString();
                this.Labanlx.Text = dr["Anlx"].ToString();
                //this.TextBox2.Text = dr["Zy"].ToString();

                departid = dr["departid"].ToString();
                year = dr["year"].ToString();
                if(!String.IsNullOrEmpty(dr["LastModifedTime"].ToString()))
                {
                    this.LabTBRQ.Text="最后更新日期：" + dr["LastModifedTime"].ToString();
                }

            }            
        }

        private void GetAnlx()
        {
            if (!string.IsNullOrEmpty(Request.QueryString["anlx"]))
            {
                string _anlx = Request.QueryString["anlx"].ToString();
                switch (_anlx)
                {
                    case "1": this.Labanlx.Text = "新闻特色专题"; break;
                    case "2": this.Labanlx.Text = "政府审批事项"; break;
                    case "3": this.Labanlx.Text = "政府服务事项上网比例"; break;
                    case "4": this.Labanlx.Text = "涉外服务事项"; break;
                    case "5": this.Labanlx.Text = "热点互动项目"; break;
                    case "6": this.Labanlx.Text = "网站综合管理"; break;
                }
            }
        }


        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("Yxsb.aspx?DepartID=" + departid + "&type=3");
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            //初始化
            string errMsg = "";

            //验证
            if (departid == "")
            {
                errMsg = "请选择部门！";
                return;
            }

            //保存
            YxsbFacade facade = new YxsbFacade();

            yxsbb exam = null;

            if (key != "")
            {
                exam = facade.Retrieve("id", key) as yxsbb;
                exam.ID = key;               
            }
            else
            {
                exam = new yxsbb();
                exam.ID = System.Guid.NewGuid().ToString();
                

                exam.CreateTime = System.DateTime.Now.ToString();
                exam.Creator = userid;

            }

            exam.Year = year;
            exam.DepartID = departid;
            exam.Title = this.TextBox1.Text;
            exam.Content = FCKeditor1.Value;
            exam.Anlx = this.Labanlx.Text;
            //exam.Zy = this.TextBox2.Text;

            exam.LastModifedTime = System.DateTime.Now.ToString();
            exam.LastModifed = userid;

            long returnValue = 0;
            if (key != "")
            {
                returnValue = facade.Update(exam);
            }
            else
            {
                returnValue = facade.Save(exam);

                ViewState["id"] = exam.ID;
            }
            uploadFile();

            if (returnValue >= 0)
            {
                errMsg = "保存成功！";
                //3.历史表更新
                errMsg += HistorySave();
            }
            else
                errMsg = "保存失败！";

            if (Request.Params["ajax"] == "true")
            {
                Response.Redirect(String.Format("YxsbAjaxSave.ashx?id={0}", exam.ID));
            }
            Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('" + errMsg + "');location.href='Yxsb.aspx?departid=" + departid + "&type=3';</script>");
        }

        #region "历史表更新"

        private string HistorySave()
        {
            HistoryExam hisexam = new HistoryExam();
            HistoryExamFacade facade = new HistoryExamFacade();
            hisexam.ID = System.Guid.NewGuid().ToString();
            hisexam.ExamID = key;
            hisexam.Type = ExamType.网站特色项目申报表.ToString();
            hisexam.Year = year;
            hisexam.DepartID = departid;
            hisexam.ModifiedID = this.userid;
            hisexam.ModifiedDate = System.DateTime.Now.ToString();

            int returnValue = facade.InsertHistory(hisexam);

            if (returnValue < 0)
                return "更新历史表报错！";

            return "";

        }
        #endregion


        #region "upload"
        public string uploadFile()
        {
            string val = Request.Params["fileUploader9_hdnFileVal"];
            List<SysAttachment> _attachments = new List<SysAttachment>();
            int returnValue = -1;
            string del = "";

            NrbzFacade facade = new NrbzFacade();

            //附件6
            if (!string.IsNullOrEmpty(val))
            {
                _attachments = NewUpload(val);
                returnValue = facade.InsertAttachment(key, 9, _attachments);
            }

            del = Request.Params["fileUploader9_del"];
            if (!string.IsNullOrEmpty(del))
                returnValue = facade.DeleteAttachment(del);

           
            if (!string.IsNullOrEmpty(del))
                returnValue = facade.DeleteAttachment(del);

            if (returnValue < 0)
            {
                return "文件上传成功，保存有误！";
            }

            return "";
        }
        public List<SysAttachment> NewUpload(string sFilePath)
        {

            List<SysAttachment> attList = new List<SysAttachment>();

            SysAttachment att = new SysAttachment();
            string[] a = sFilePath.Split(',');
            for (int i = 0; i < a.Length; i++)
            {
                string[] b = a[i].Split(';');
                if (b.Length > 1)
                {
                    string tmpVirtualPath = HttpContext.Current.Server.MapPath(b[0].ToString());
                    FileInfo f = new System.IO.FileInfo(tmpVirtualPath);
                    att = new SysAttachment();
                    att.FileName = b[1].ToString();
                    att.FilePath = f.Name;
                    att.FileSize = f.Length.ToString();
                    att.Extension = f.Extension;
                    attList.Add(att);

                    string fileName = HttpContext.Current.Server.MapPath(GlobalParams.Instance.AttachmentUploadUrl) + f.Name;
                    if (!File.Exists(fileName))
                    {
                        f.MoveTo(fileName);
                    }
                }
            }
            return attList;

        }
        public string UploadPath
        {
            get { return PageGlobalParams.PageUrlBase2 + GlobalParams.Instance.AttachmentUploadUrl; }
        }
        #endregion
    }
}
